package com.argticling.dao.impl;

import com.argticling.dao.impl.hibernate.HibernateUtil;
import com.argticling.dao.interf.ArticleDAO;
import com.argticling.model.Article;
import com.argticling.model.DublinCore;
import com.argticling.model.ImageArticleFragment;
import com.argticling.model.TextArticleFragment;
import com.argticling.model.User;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;

public class ArticleDAOImplementation extends AbstractDAOImplementation implements ArticleDAO {
    private TextFragmentDAOImplementacion textFragmentDao;
    private ImageFragmentDAOImplementacion imageFragmentDao;

    
    public void persist(Article article) {
        new HibernateUtil().persist(article);

    }

    public ImageFragmentDAOImplementacion getImageFragmentDao() {
        return imageFragmentDao;
    }

    public void setImageFragmentDao(ImageFragmentDAOImplementacion imageFragmentDao) {
        this.imageFragmentDao = imageFragmentDao;
    }

    public TextFragmentDAOImplementacion getTextFragmentDao() {
        return textFragmentDao;
    }

    public void setTextFragmentDao(TextFragmentDAOImplementacion textFragmentDao) {
        this.textFragmentDao = textFragmentDao;
    }
    
    public List<Article> getLastArticles(List<DublinCore> dublinCores){
    	List<Article> articles = new ArrayList<Article>();
    	for(DublinCore dc : dublinCores){
    		Article article = getByDC(dc.getId());
    		if(article.isPublished()){
    			articles.add(getByDC(dc.getId()));
    		}
    	}
    	return articles;
    }
    
    public Article getByDC(String dc){
    	Session session = new HibernateUtil().getSession();
        Article article = (Article) session.createQuery("from Article as " +
                "article where article.dc=?").setString(0, dc).uniqueResult();
        return article;
    }

	public Article getById(String id) {
		 return (Article) new HibernateUtil().getSession().createQuery("FROM Article as article where " +
         "article.id = ?").setString(0, id).uniqueResult();
	}
	
    public void delete(String articleId) {
        HibernateUtil.beginTransaction();

        Article article = (Article) HibernateUtil.getSession().createQuery("from Article as " +
                "article where article.id = ?").setString(0, articleId).uniqueResult();

        HibernateUtil.getSession().delete(article);
        HibernateUtil.commitTransaction();
    }

}